package com.lck.tutor.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lck.tutor.common.BaseResponse;
import com.lck.tutor.common.ErrorCode;
import com.lck.tutor.common.Result;
import com.lck.tutor.model.domain.Follow;
import com.lck.tutor.model.domain.User;
import com.lck.tutor.service.FollowService;
import com.lck.tutor.mapper.FollowMapper;
import com.lck.tutor.service.UserService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author Administrator
* @description 针对表【follow(用户关注表)】的数据库操作Service实现
* @createDate 2022-10-30 15:34:09
*/
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow>
implements FollowService{

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private UserService userService;

    @Override
    public BaseResponse<?> follow(Long followUserId, Boolean isFollow, User loginUser) {
        //获取登录用户
        Long userId = loginUser.getId();
        String key = "follow:"+userId;
        //判断到底是关注还是取关
        if (isFollow){
            //关注，新增数据
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setUserFollowId(followUserId);
            boolean isSuccess = save(follow);
            if (isSuccess){
                stringRedisTemplate.opsForSet().add(key,followUserId.toString());
            }
            return Result.success("已关注");
        } else {
            //取关，删除
            QueryWrapper<Follow> wrapper = new QueryWrapper<>();
            wrapper.eq("userId",userId);
            wrapper.eq("userFollowId",followUserId);
            boolean isSuccess = remove(wrapper);
            if (isSuccess){
                stringRedisTemplate.delete(key);
            }
            return Result.success("已取消关注");
        }
    }

    /**
     * 获取共同关注列表
     * @param id
     * @param userId
     * @return
     */
    @Override
    public BaseResponse<List<User>> common(Long id, Long userId) {
        //求交集
        String key1 = "follow:" + id;
        String key2 = "follow:" + userId;
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(key1, key2);
        //捷信id集合
        if (intersect == null || intersect.isEmpty()){
            return Result.success(Collections.emptyList());
        }
        List<Long> idList = intersect.stream().map(Long::valueOf).collect(Collectors.toList());
        //查询用户
        List<User> userList = userService.query().in("id", idList).list().stream().map(userService::getSafetyUser).collect(Collectors.toList());
        return Result.success(userList);
    }
}
